package com.demo.service;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @description:
 * 1. 实现MethodInterceptor接口
 * 2. 创建Enhancer  设置superClass  设置callback
 *
 * 优点: 不需要实现接口
 * @author: ayouman
 * @date: 2024/6/28 17:25
 */
public class UserServiceCglibProxy implements MethodInterceptor {
    public IUserService getProxy(Class<?> clazz) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(clazz);
        enhancer.setCallback(this);
        return (IUserService) enhancer.create();
    }
    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("方法执行之前");
        Object result = methodProxy.invokeSuper(o, objects);
        System.out.println("方法执行之后");
        return result;
    }
}
